package com.aisi.backend.service.impl;

import com.aisi.backend.mapper.AccountDetailsMapper;
import com.aisi.backend.mapper.AccountMapper;
import com.aisi.backend.service.ImageService;
import com.aisi.backend.utils.MybatisUtil;
import io.minio.*;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.Part;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.UUID;

/**
 * @Author: shenjianZ
 * @Date: 2024/5/12 上午8:31
 * @Description:
 */


public class ImageServiceImpl implements ImageService {

    MinioClient minioClient = MinioClient.builder().
            endpoint("http://43.143.145.172:9001")
            .credentials("admin", "admin123456")
            .build();

    private SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");


    @Override
    public String uploadImage(Part filePart, Integer userId) throws IOException {
        String imageName = UUID.randomUUID().toString().replace("-", "");
        imageName = "/avatar/" + imageName;
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket("campus")
                .stream(filePart.getInputStream(), filePart.getSize(), -1)
                .object(imageName)
                .build();



        try {
            minioClient.putObject(args);
            try (SqlSession session = MybatisUtil.getSqlSession(true)) {
                AccountMapper mapper = session.getMapper(AccountMapper.class);
                String avatar = mapper.findAccountById(userId).getAvatar();
                if (avatar != null)
                    deleteOldAvatar(avatar);
                Integer i = mapper.updateAccountAvatar(userId, imageName);
                if (i > 0) return imageName;
                else return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void fetchImageFromMinio(ServletOutputStream outputStream, String imagePath) throws Exception {
        GetObjectArgs args = GetObjectArgs.builder()
                .bucket("campus")
                .object(imagePath)
                .build();
        GetObjectResponse response = minioClient.getObject(args);
        IOUtils.copy(response, outputStream);
    }

    private void deleteOldAvatar(String avatar) throws Exception {
        if (avatar == null || avatar.isEmpty()) return;
        RemoveObjectArgs remove = RemoveObjectArgs.builder()
                .bucket("campus")
                .object(avatar)
                .build();
        minioClient.removeObject(remove);
    }
}
